package com.wuzheng.wisgo.sanitation.cloud.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.person.User;
import com.wuzheng.wisgo.sanitation.cloud.service.person.UserService;
import com.wuzheng.wisgo.sanitation.framework.base.annotation.Authorization;
import com.wuzheng.wisgo.sanitation.framework.base.annotation.IgnoreAuthorization;
import com.wuzheng.wisgo.sanitation.cloud.constant.ErrorConst;
import com.wuzheng.wisgo.sanitation.framework.core.constant.SysConst;
import com.wuzheng.wisgo.sanitation.framework.core.constant.SysRespEnum;
import com.wuzheng.wisgo.sanitation.framework.core.util.ServiceAssert;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author：hibon
 * @date：Created in 2019/10/11
 * @description：认证拦截器
 * @modified By：
 * @version: 1.0
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有ignoreAuthorization注释，有则跳过认证
        if (method.isAnnotationPresent(IgnoreAuthorization.class)) {
            IgnoreAuthorization ignoreAuthorization = method.getAnnotation(IgnoreAuthorization.class);
            if (ignoreAuthorization.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(Authorization.class)) {
            Authorization authorization = method.getAnnotation(Authorization.class);
            if (authorization.required()) {
                // 执行认证
                ServiceAssert.notNull(token, SysRespEnum.MISSING_ARGUMENT.getCode(), ErrorConst.User.TOKEN_LOST);
                // 获取 token 中的 user id
                String userId = null;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    ServiceAssert.isTrue(false, SysRespEnum.ILLEGAL_ACCESS.getCode(),
                            SysRespEnum.ILLEGAL_ACCESS.getMessage());
                }
                User user = userService.selectById(userId);
                ServiceAssert.notNull(user, SysRespEnum.SERVICE_EXCEPTION.getCode(), ErrorConst.User.NAME_OR_PWD_ERROR);
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SysConst.TOKEN_SECRET)).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    ServiceAssert.isTrue(false, SysRespEnum.ILLEGAL_ACCESS.getCode(),
                            SysRespEnum.ILLEGAL_ACCESS.getMessage());
                }
                return true;
            }
        }
        return true;
    }
}
